package com.motong.gongdan.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.entity.CustomField;
import com.motong.gongdan.entity.MatchingRule;
import com.motong.gongdan.mapper.CustomFieldMapper;
import com.motong.gongdan.util.MongoUtils;
import com.motong.gongdan.util.OwnUtil;
import com.motong.gongdan.util.StringUtil;
import com.motong.gongdan.vo.system.CustomField.ColumnsConfigure;
import com.motong.gongdan.vo.system.CustomField.ColumnsConfigureList;
import com.motong.gongdan.vo.system.otherVo.CustomFieldVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:fff
 * @time:2022/4/12
 */
@Slf4j
@Service
public class CustomFieldService extends ServiceImpl<CustomFieldMapper, CustomField> {
    @Resource
    CustomFieldService customFieldService;
    @Resource
    MatchingRuleService matchingRuleService;

    @Resource
    private MongoTemplate mongoTemplate;

    public List<CustomFieldVo> handleCustomFieldForList(String other) {
        JSONArray jsonArray = JSONArray.parseArray(other);
        List<CustomFieldVo> custom = jsonArray.toJavaList(CustomFieldVo.class);
        if (!CollectionUtils.isEmpty(custom)) {
            custom.forEach(c -> {
                CustomField cf = customFieldService.getById(c.getCustomFieldId());
                c.setCustomFieldMess(cf);
            });
        }
        return custom;
    }

    public JSONArray handleObjectCreateOrEdit(List<CustomFieldVo> customFieldVos) {
//        customFieldVos.forEach(c->{
//            CustomField cf = customFieldService.getById(c.getCustomFieldId());
//            cf.setInUse(1);
//            customFieldService.updateById(cf);
//        });
        JSONArray jsonArray = new JSONArray();
        JSONArray ja = JSONArray.parseArray(JSON.toJSONString(customFieldVos));
        jsonArray.addAll(ja);
        return jsonArray;
    }

    public List<ColumnsConfigure> handleDefaultColumns(String type, boolean flag) {
        String str = OwnUtil.readFileTxt("columns.txt");
        JSONArray jsonArray = JSON.parseArray(str);
        List<ColumnsConfigureList> allList = jsonArray.toJavaList(ColumnsConfigureList.class);
        String finalType = type;
        List<ColumnsConfigure> list = allList.stream().filter(f -> f.getType().equals(finalType)).findAny().orElse(null).getColumns();
        if ("productForm".equals(type) || "salaryForm".equals(type)) {
            List<ColumnsConfigure> newList = new ArrayList<>();
            list.forEach(l -> {
                if (StringUtil.isNotBlank(l.getChineseName())) {
                    newList.add(l);
                } else if (StringUtil.isBlank(l.getChineseName())) {
                    List<CustomField> customFieldList = customFieldService.list(new QueryWrapper<CustomField>()
                            .eq("field_ascription", l.getName()).ne("field_type", "upload")
                            .ne(flag, "field_type", "relevanceProp").orderByAsc("field_ascription"));
                    handleReturnList(newList, customFieldList);
                }
            });
            return newList;
        }
        //出库
        if ("stockIn".equals(type) || "stockOut".equals(type)) {
            type = "stock";
            // 库存
        } else if ("stockBalance".equals(type)) {
            type = "product";
        } else if ("assemblyDetail".equals(type)){
            type = "workOrder";
        }
        // 获取自定义字段
        List<CustomField> customFieldList = customFieldService.list(new QueryWrapper<CustomField>()
                .eq("field_ascription", type.equals("mission") ? "processes" : type)
                .ne("field_type", "upload").ne(flag, "field_type", "relevanceProp").orderByAsc("field_ascription"));
        // 库存详情
        if ("stockMsg".equals(type)) {
            List<String> ascription = new ArrayList<>();
            ascription.add("stockMsg");
            ascription.add("stock");
            customFieldList = customFieldService.list(new QueryWrapper<CustomField>().in("field_ascription", ascription)
                    .ne("field_type", "upload").ne(flag, "field_type", "relevanceProp").orderByAsc("field_ascription"));
        }
        // 修改库存
        if ("stockHandle".equals(type)) {
            customFieldList = customFieldService.list(new QueryWrapper<CustomField>().eq("field_ascription", "stockMsg")
                    .ne("field_type", "upload").ne(flag, "field_type", "relevanceProp").orderByAsc("field_ascription"));
        }
        if ("formInProductO".equals(type) || "formInProduct".equals(type)) {
            customFieldList = customFieldService.list(new QueryWrapper<CustomField>().eq("field_ascription", "workOrder")
                    .ne("field_type", "upload").ne(flag, "field_type", "relevanceProp").orderByAsc("field_ascription"));
        }
        handleReturnList(list, customFieldList);
        return list;
    }

    public static void handleReturnList(List<ColumnsConfigure> newList, List<CustomField> customFieldList) {
        if (!CollectionUtils.isEmpty(customFieldList)) {
            customFieldList.forEach(c -> {
                ColumnsConfigure cc = new ColumnsConfigure();
                cc.setName(c.getId().toString());
                cc.setChineseName(c.getChineseName());
                cc.setState(true);
                cc.setType(c.getFieldType());
                cc.setSort(c.getSort());
                newList.add(cc);
            });
        }
    }

    public List<ColumnsConfigure> handleImportDefault(String type) {
        String str = OwnUtil.readFileTxt("importModelColumns.txt");
        JSONArray jsonArray = JSON.parseArray(str);
        List<ColumnsConfigureList> allList = jsonArray.toJavaList(ColumnsConfigureList.class);
        if (allList.stream().filter(f -> f.getType().equals(type)).findAny().orElse(null) != null) {
            return allList.stream().filter(f -> f.getType().equals(type)).findAny().orElse(null).getColumns();
        }
        return null;
    }


    public List<ColumnsConfigure> wagesRedisHandle() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/test/wagesHeader.txt")));
        String line;
        line = br.readLine();
        JSONArray jsonArray = JSONArray.parseArray(line);
        List<MatchingRule> matchingRules = matchingRuleService.list(new QueryWrapper<MatchingRule>().eq("state", 1));
        List<ColumnsConfigure> columnsConfiguresNew = new ArrayList<>();
        List<ColumnsConfigure> columnsConfigures = jsonArray.toJavaList(ColumnsConfigure.class);
        columnsConfigures.forEach(c -> {
            if (StringUtil.isBlank(c.getChineseName())) {
                matchingRules.forEach(m -> {
                    ColumnsConfigure cc = new ColumnsConfigure();
                    cc.setState(true);
                    cc.setName(m.getCusField());
                    if (StringUtils.isNumeric(m.getCusField())) {
                        CustomField cf = customFieldService.getById(Integer.valueOf(m.getCusField()));
                        if (Objects.nonNull(cf)) {
                            cc.setChineseName(cf.getChineseName());
                        }
                    } else {
                        cc.setChineseName(m.getAttribute());
                    }
                    columnsConfiguresNew.add(cc);
                });
            } else {
                columnsConfiguresNew.add(c);
            }
        });
        return columnsConfiguresNew;
    }

    /**
     * 查询自定义字段(并返回对象id)
     */
    public List<Integer> searchCustomField(Map<Integer, String> customMap, String BelongModule) {
        List<Integer> ids = Optional.of(MongoUtils.getSearchResult(customMap, BelongModule, customFieldService, mongoTemplate))
                .orElse(new ArrayList<>(1)).stream().map(j -> {
                    try {
                        JSONObject jsonObj = JSONUtil.parseObj(j);
                        return jsonObj.get("_id", Integer.class);
                    } catch (Exception e) {
                        log.error("发生异常json: {}", j);
                        e.printStackTrace();
                    }
                    return null;
                }).filter(Objects::nonNull)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            ids.add(0);
        }
        return ids;
    }
}
